<?php
/**
 * Created by PhpStorm.
 * User: 554665488
 * Date: 2018-6-24
 * Time: 16:02
 * @description:服务端
 * @Author: yfl
 * @QQ 554665488
 */
$server = new Swoole\Server('0.0.0.0', 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);

$server->on('connect', function ($serv, $fd) {
    echo "有新的客户端连接，连接标识为$fd" . PHP_EOL;
});

$server->on('receive', function ($serv, $fd, $from_id, $data) {
    //使用同步客户端
//    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
//
//
//    $client->connect('127.0.0.1', 9502) || exit('connect fail' . $client->errCode);
//    //向服务端2发送数据
//    $client->send($data + 1);
//
//    $response = $client->recv();
//    //向第一个客户端发送数据
//    $serv->send($fd, '服务端2结果' . $response);
//
//    $client->close();

    //使用异步客户端
    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
    //连接服务端
    $client->on("connect", function (swoole_client $cli) use ($data) {
        $cli->send($data + 1);
    });
    //接收到服务端发送的消息时触发的
    $client->on('receive', function ($cli, $data) use ($serv, $fd) {
        $serv->send($fd, $data);
    });
    $client->on('error', function ($cli) {
    });
    //监听连接关闭事件,客服端关闭，或者服务器主动关闭
    $client->on('close', function ($cli) {

    });
    //先绑定事件之后随后建立连接，连接失败直接退出并打印错误码
    $client->connect('127.0.0.1', 9502) || exit("connect failed. Error: {$client->errCode}\n");

});

$server->on('close', function ($serv, $fd) {
    echo "编号为{$fd}的客户端已经关闭." . PHP_EOL;
});


$server->start();
